﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.YouTube
{
    public class YouTubeService
    {
        private YouTubeConfig _config;

        public YouTubeService(string config)
        {
            _config = config.DeserializeJsonTo<YouTubeConfig>();
        }

        public IList<YouTubeVideo> GetVideos()
        {
            var urlFormat = "";

            switch(_config.FeedType)
            {
                case YouTubeFeedType.Search:
                    urlFormat = "http://gdata.youtube.com/feeds/base/videos?q={0}&alt=rss&v=2&orderby={1}&safeSearch={2}&client=ytapi-youtube-search&max-results=50";
                    break;
                case YouTubeFeedType.User:
                    urlFormat = "http://gdata.youtube.com/feeds/base/users/{0}/uploads?alt=rss&v=2&orderby={1}&safeSearch={2}&client=ytapi-youtube-profile&max-results=50";
                    break;
                default:
                    throw new Exception("Unknown feed type");
            }

            var feed = XDocument.Load(string.Format(urlFormat,
                _config.Query,
                _config.OrderBy.ToString().ToLower(),
                _config.SafeSearch.ToString().ToLower()));

            if (feed.Root == null)
                return null;

            return feed.Root.Element("channel").Descendants("item").Select(el => el.ToYouTubeVideo()).ToList();
        }

        public YouTubeVideo GetVideo(string id)
        {
            var feed = XDocument.Load(string.Format("http://gdata.youtube.com/feeds/base/videos/{0}?alt=rss&v=2", id));

            if (feed.Root == null)
                return null;

            return feed.Root.ToYouTubeVideo();
        }

        public string GetVideoEmbedCode(string id)
        {
            return GetVideoEmbedCode(id, 640, 385, 2, 0, 0, 0, "", "", 1, 0, 0, 0, 0, 0, 1, 0, "", "", "", 1, 1, 1, 0, "opaque");
        }

        public string GetVideoEmbedCode(string id,
            int width,
            int height,
            int autohide,
            int autoplay,
            int border,
            int cc_load_policy,
            string color1,
            string color2,
            int controls,
            int disablekb,
            int egm,
            int enablejsapi,
            int fs,
            int hd,
            int iv_load_policy,
            int loop,
            string origin,
            string playerapiid,
            string playlist,
            int rel,
            int showinfo,
            int showsearch,
            int start,
            string wmode)
        {
            var url = "http://www.youtube.com/v/" + id + "&version=3";

            if (autohide != 2) url += "&autohide=" + autohide;
            if (autoplay != 0) url += "&autoplay=" + autoplay;
            if (border != 0) url += "&border=" + border;
            if (cc_load_policy != 0) url += "&cc_load_policy=" + cc_load_policy;
            if (!string.IsNullOrEmpty(color1)) url += "&color1=" + color1;
            if (!string.IsNullOrEmpty(color2)) url += "&color2=" + color2;
            if (controls != 1) url += "&controls=" + controls;
            if (disablekb != 0) url += "&disablekb=" + disablekb;
            if (egm != 0) url += "&egm=" + egm;
            if (enablejsapi != 0) url += "&enablejsapi=" + enablejsapi;
            if (fs != 0) url += "&fs=" + fs;
            if (hd != 0) url += "&hd=" + hd;
            if (iv_load_policy != 1) url += "&iv_load_policy=" + iv_load_policy;
            if (loop != 0) url += "&loop=" + loop;
            if (!string.IsNullOrEmpty(origin)) url += "&origin=" + origin;
            if (!string.IsNullOrEmpty(playerapiid)) url += "&playerapiid=" + playerapiid;
            if (!string.IsNullOrEmpty(playlist)) url += "&playlist=" + playlist;
            if (rel != 1) url += "&rel=" + rel;
            if (showinfo != 1) url += "&showinfo=" + showinfo;
            if (showsearch != 1) url += "&showsearch=" + showsearch;
            if (start != 0) url += "&start=" + start;

            var embedCode = "<object width=\"{1}\" height=\"{2}\">"; 
            embedCode += "<param name=\"allowFullScreen\" value=\"true\"></param>"; 
            embedCode += "<param name=\"allowScriptAccess\" value=\"always\"></param>";
            embedCode += "<param name=\"movie\" value=\"{0}\" />";
            embedCode += "<param name=\"wmode\" value=\"{3}\" />"; 
            embedCode += "<embed src=\"{0}\" type=\"application/x-shockwave-flash\" width=\"{1}\" height=\"{2}\" allowfullscreen=\"true\" allowscriptaccess=\"always\" wmode=\"{3}\"></embed>";
            embedCode += "</object>";

            return string.Format(embedCode,
                url,
                width,
                height,
                wmode);
        }

        
    }

    #region Model

    public class YouTubeVideo
    {
        public string Id { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string ThumbnailSmall1 { get; set; }
        public string ThumbnailSmall2 { get; set; }
        public string ThumbnailSmall3 { get; set; }
        public string ThumbnailLarge { get; set; }
        public DateTime Published { get; set; }
        public string Author { get; set; }
    }

    #endregion
}